﻿using System;
using System.Configuration;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Threading;
using CommandRunner.Contract;
using CommandRunner.WCFDataTransport;
using NLog;

namespace CommandRunner.Server
{
    public class Server
    {
        private readonly int _port = int.Parse(ConfigurationManager.AppSettings["Port"]);
        private readonly IPAddress _ip = IPAddress.Parse(ConfigurationManager.AppSettings["IP"]);
        private Logger _log { get { return LogManager.GetCurrentClassLogger(); } }

        private bool _run;
        private ServiceHost _host;

        public Server()
        {
            _host = new ServiceHost(typeof(CommandRunnerServer), new Uri(String.Format("net.tcp://{0}:{1}/CommandRunner", _ip, _port)));
            _host.AddServiceEndpoint(typeof(ICommandRunnerServer), new NetTcpBinding(SecurityMode.None), "");
        }

        public static void Main(string[] args)
        {
            Server server = new Server();
            server.Start();
        }

        public void Stop()
        {
            _log.Info("Command Runner Server Stopping");
            _run = false;
            _host.Close();
            _log.Info("Command Runner Server Stopped");
        }

        public void Start()
        {
            _log.Info("Command Runner Server Starting");
            Console.CancelKeyPress += delegate { Stop(); };
            _run = true;
            _host.Open();

            foreach (ServiceEndpoint sep in _host.Description.Endpoints)
            {
                _log.Debug("Listening on: {0}", sep.ListenUri.AbsoluteUri);
            }

            _log.Info("Command Runner Server Started");

            while (_run)
            {
                Thread.Sleep(1000);
            }
        }
    }
}
